package org.example.controller;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义异常(只针对sentinel)-全局拦截
 */
@Component
public class ExceptionHandlerPage implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=utf-8");
        ResultData resultData = null;
        if (e instanceof FlowException){ //限流
            resultData = new ResultData(-1,"接口被限流了");
        }else if (e instanceof DegradeException){ //降级
            resultData = new ResultData(-2,"接口被降级了");
        }else if (e instanceof ParamFlowException){ //参数限流异常
            resultData = new ResultData(-3,"参数限流异常");
        }else if (e instanceof AuthorityException){ //授权异常
            resultData = new ResultData(-4,"授权异常");
        }else if (e instanceof SystemBlockException){ //接口降级
            resultData = new ResultData(-5,"系统负载异常");
        }
        httpServletResponse.getWriter().write(JSON.toJSONString(resultData));
    }
}
@Data
@AllArgsConstructor
@NoArgsConstructor
class ResultData{
    private int code;
    private String message;
}

